<?php

define("IN_SYS", true);

class IndexAction extends CommonAction {
	
	public function topN() {
		$Config = M('Config');
		$cfg_topn_num = $Config->where("varname='cfg_topn_num'")->getField('value');
		if (!$cfg_topn_num || empty($cfg_topn_num)) {
			$cfg_topn_num = 10;
		}
	
		$sql = "select u.id as uid,u.username as username,u.realname as realname,u.headimgurl as headimgurl,u.userphone as userphone,u.is_exchange as is_exchange,
				s.score as score,u.wxid as wxid,u.regtime
				from tp_user u join tp_score s on u.id=s.uid order by score desc limit ".$cfg_topn_num;
		$result = $Config->query($sql);
	
		$hasTopn = 0;
		if ($result && count($result) > 0) {
			$hasTopn = 1;
	
			foreach ($result as $row) {
				if (!empty($row['userphone']) && $row['userphone'] != 'none') {
					$row['userphone'] = substr_replace($row['userphone'],'****',3,4);
				} else {
					$row['userphone'] = '未填写';
				}
	
				if (empty($row['username']) || $row['username'] == '') {
					$row['username'] = "&nbsp;&nbsp;";
				}
	
				$data[] = $row;
			}
			//$this->assign("data", $data);
			//$this->assign("dataSize", count($data));
		}
	
		//$this->assign("hasTopn", $hasTopn);
		//$this->assign("cfg_topn_num", $cfg_topn_num);
		
		
		echo json_encode($data);
		exit;
		
	
		/* //获取微信分享图片，分享标题，分享描述，分享URL
		$cfg_wx_share_title = $Config->where("varname='cfg_wx_share_title'")->getField('value');
		$this->assign('cfg_wx_share_title',$cfg_wx_share_title);
	
		$cfg_wx_share_desc = $Config->where("varname='cfg_wx_share_desc'")->getField('value');
		$this->assign('cfg_wx_share_desc',$_SESSION['shareDesc']);
	
		$cfg_wx_share_pic = $Config->where("varname='cfg_wx_share_pic'")->getField('value');
		$this->assign('cfg_wx_share_pic',$cfg_wx_share_pic);
	
		$cfg_wx_share_url = $Config->where("varname='cfg_wx_share_url'")->getField('value');
		$this->assign('cfg_wx_share_url',$cfg_wx_share_url);
	
		$cfg_wx_share_redirect = $Config->where("varname='cfg_wx_share_redirect'")->getField('value');
		$this->assign('cfg_wx_share_redirect',$cfg_wx_share_redirect);
	
		$cfg_appid = $Config->where("varname='cfg_appid'")->getField('value');
		$cfg_screct = $Config->where("varname='cfg_screct'")->getField('value');
		// 获取分享的签名 开始
		vendor("WeixinShare.jssdk");
		$jssdk = new JSSDK($cfg_appid, $cfg_screct);
		$signPackage = $jssdk->GetSignPackage();
		$this->assign('signPackage',$signPackage);
		// 获取分享的签名 结束
	
		$this->display(); */
		
		
		
		
	}
	
	private function setCookieVal($cookieStr) {
		$cookieName = "guaguakaCookie";
		// setcookie("wxidCookie4", $cookieStr, time() + 60*60*24*100);
		// setcookie("wxidCookie4", $cookieStr, time() + 2*60);
		cookie($cookieName,$cookieStr,array('expire'=>3600 * 24 * 3000));// 3600秒
	}
	
	public function setCookieValExpire() {
		$cookieName = "guaguakaCookie";
		cookie($cookieName,null);
	}
	
	private function setCookieVal2($cookieName, $cookieStr) {
		// setcookie("wxidCookie4", $cookieStr, time() + 60*60*24*100);
		// setcookie("wxidCookie4", $cookieStr, time() + 2*60);
		cookie($cookieName,$cookieStr,array('expire'=>3600 * 24 * 3000));// 3600秒
	}
	
	public function setCookieValExpire2($cookieName) {
		cookie($cookieName,null);
	}
	
	public function setShareCount() {
		$Config = M('Config');
		$flag = $Config->execute("update tp_config as c set c.value=c.value+1 where c.varname='cfg_share_count'");
		
		if ($flag) {
			echo json_encode(array('success'=>'ok','msg'=>'分享计数成功！'));
		} else {
			echo json_encode(array('success'=>'ng','msg'=>'分享计数失败！'));
		}
		
		exit;
	}
	
	public function saveInfo() {
		// 检测是否完成助力
		$Friend = M('Friend');
		$shareCount = $Friend->where("uid=".$_SESSION['uid']." and fid != 0")->count();
		if (intval($shareCount) < 5) {
			$Config = M('Config');
			$cfg_lqjp_zhuli = $Config->where("varname='cfg_lqjp_zhuli'")->getField('value');
			echo json_encode(array('success'=>'zhuli','msg'=>$cfg_lqjp_zhuli));
			exit;
		}
		// 检测是否完成助力 结束
		
		$userphone = $_POST['userphone'];
		$User = M('User');
		$flag = $User->execute("update tp_user as a set a.userphone='".$userphone."' where a.id='".$_SESSION['uid']."'");
		if ($flag) {
			echo json_encode(array('success'=>'ok','msg'=>'保存信息成功！'));
		} else {
			echo json_encode(array('success'=>'ng','msg'=>'保存信息失败！'));
		}
		exit;
	}
	
	/**
	 * 新流程-->跳转至关注页面(之后的流程就是：用户点击进入最原始的Index入口)
	 */
	public function toSharePage() {
		// 获取分享人的信息
		$shareId = $_REQUEST['shareId'];
		// 写入session
		session("shareId", $shareId);
		// 获取关注页面的地址
		$Config = M('Config');
		$cfg_toshare_page = $Config->where("varname='cfg_toshare_page'")->getField('value');
		
		$User = M('User');
		
		//判断活动是否结束
		if($this->isGameEnd()) {
				
			$cfg_game_finish=$Config->where("varname='cfg_game_finish'")->getField('value');
				
				
			$this->assign('cfg_game_finish',$cfg_game_finish);
		
			$this->display('gameFinish');
				
		} else {
			
			
			//判断是否为微信授权模式，如果是，跳转微信授权页面
			
			$cfg_appid = $Config->where("varname='cfg_appid'")->getField('value');
			$cfg_screct = $Config->where("varname='cfg_screct'")->getField('value');
			
			$cfg_isoauth_open = $Config->where("varname='cfg_isoauth_open'")->getField('value');
			
			$need_login = 1; //默认需要弹填写信息框
			
			// 用以表示用户是否已经通过该入口流程成功获取了其个人信息
			$getInfo = 0;
			
			// 获取分享人的信息
			//$shareId = $_REQUEST['shareId'];
			// 从接收参数改成了session或者cookie获取
			//$shareId = $_SESSION['shareId'];
			
			//
			//$cfg_isoauth_open = 0;
			
			if($cfg_isoauth_open=='1') {
				$cfg_oauth_cb_url = $Config->where("varname='cfg_oauth_cb_url2'")->getField('value');
				// 拼接分享人的信息
				$cfg_oauth_cb_url .= '?shareId='.$shareId;
					
					
				//授权判断
				if (empty($openid)){
					if (empty($_REQUEST["code"])) {
						$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$cfg_appid."&redirect_uri=".urlencode($cfg_oauth_cb_url)."&response_type=code&scope=snsapi_userinfo&state=blinq#wechat_redirect";
			
						redirect($url);
							
					}else{
						$code = $_REQUEST['code'];
			
						$accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $cfg_appid . "&secret=" . $cfg_screct . "&code=$code&grant_type=authorization_code";
						$ch = curl_init($accessTokenUrl);
						curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						//curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');
						curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
						curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
						$info = curl_exec($ch);
						$dataJson = json_decode($info, true);
						$openid = $dataJson['openid'];
						$access_token = $dataJson['access_token'];
						session("wxid", $openid);
							
						//
						$cookieStr = '{"openid":"'.$openid.'","date":"20111212"}';
						$this->setCookieVal($cookieStr);
							
						// 拉取用户信息
						$userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
						$ch = curl_init($userInfoUrl);
						curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						//curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');
						curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
						curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
						$info = curl_exec($ch);
						$dataJson = json_decode($info, true);
							
						$headimgurl = $dataJson['headimgurl'];
						$nickname = $dataJson['nickname'];
							
							
						// 判断wxid是否已经配置过，如果存在并且填写过信息，则不需要显示填写信息框
							
						$condition['wxid'] = $openid;
						$userList = $User->where($condition)->find();
							
						$this->assign("headimgurl",$info); // 调试之用
							
						
						if($userList && count($userList) > 0){
							$userphone = $userList['userphone'];
							if (!empty($userphone) && $userphone != 'none') {
								$need_login = 0; //表示填写过信息，不需要显示填写信息框
							}
			
							//获取用户ID
							$uid = $userList['id'];
							session("uid",$uid);
			
							//
							if (!empty($nickname)) {
								$userList['username'] = $nickname;
								$userList['headimgurl'] = $headimgurl;
								$User->save($userList);
								$getInfo = 1;
							}
			
						} else {
							$userdata['username'] = $nickname;
							$userdata['userphone'] = 'none';
							$userdata['is_exchange'] = '0';
							$userdata['wxid'] = $openid;
							$userdata['headimgurl'] = $headimgurl;
							$userdata['regtime'] = date("Y-m-d H:i:s");
							$uid = $User->add($userdata);
							session("uid",$uid);
							
							$getInfo = 1;
						}
							
						//
						if ($shareId != '' && $shareId != '0' && $shareId != $_SESSION['uid']) {
							$Friend = M('Friend');
							$f_arr['uid']=$shareId;
							$f_arr['fid']=$_SESSION['uid'];
							$shareResult = $Friend->where($f_arr)->find();
							if (empty($shareResult) || $shareResult['uid'] == '') {
									$f_arr['sharetime'] = date("Y-m-d H:i:s");
									$Friend->add($f_arr);
		
		
							}
			
						}
							
							
							
							
							
				}
				}
				} else {
					
						/* session("wxid", "oAMbVsyj3BblAIbtg6KmDpDIhdkI");
						session("uid", "20"); */
		
				}
			
			
			
			
		}
		
		
		
		
		// 往session设置getInfo
		session("getInfo", $getInfo);
		
		
		
		
		// 跳转到关注页面
		header("Location: ".$cfg_toshare_page);
	}
	
	public function indexShuqian() {
		$Config = M('Config');
		$User = M('User');
		$uploadDir = "__PUBLIC__/Uploads/";
		
		//获取微信分享图片，分享标题，分享描述，分享URL
		$cfg_wx_share_title = $Config->where("varname='cfg_wx_share_title'")->getField('value');
		$this->assign('cfg_wx_share_title',$cfg_wx_share_title);
		
		$cfg_wx_share_desc = $Config->where("varname='cfg_wx_share_desc'")->getField('value');
		$this->assign('cfg_wx_share_desc',$cfg_wx_share_desc);
		
		$cfg_wx_share_pic = $Config->where("varname='cfg_wx_share_pic'")->getField('value');
		//$this->assign('cfg_wx_share_pic',$baseDomain."Public/Uploads/".$cfg_wx_share_pic);
		$this->assign('cfg_wx_share_pic',$cfg_wx_share_pic);
		
		$cfg_wx_share_url = $Config->where("varname='cfg_wx_share_url'")->getField('value');
		$this->assign('cfg_wx_share_url',$cfg_wx_share_url);
		
		
		$cfg_wx_share_redirect = $Config->where("varname='cfg_wx_share_redirect'")->getField('value');
		$this->assign('cfg_wx_share_redirect',$cfg_wx_share_redirect);
		
		//判断活动是否结束
		if($this->isGameEnd()){
				
			$cfg_game_finish=$Config->where("varname='cfg_game_finish'")->getField('value');
				
				
			$this->assign('cfg_game_finish',$cfg_game_finish);
		
			$this->display('gameFinish');
				
		} else {
			
			//获取首页的标题
			$cfg_homepage_title = $Config->where("varname='cfg_homepage_title'")->getField('value');
			$this->assign('cfg_homepage_title',$cfg_homepage_title);
			
			//获取统计代码
			$cfg_tongji_code = $Config->where("varname='cfg_tongji_code'")->getField('value');
			$this->assign('cfg_tongji_code',$cfg_tongji_code);
			
			$cfg_appid = $Config->where("varname='cfg_appid'")->getField('value');
			$cfg_screct = $Config->where("varname='cfg_screct'")->getField('value');
			
			// 获取分享的签名 开始
			vendor("WeixinShare.jssdk");
			$jssdk = new JSSDK($cfg_appid, $cfg_screct);
			$signPackage = $jssdk->GetSignPackage();
			$this->assign('signPackage',$signPackage);
			// 获取分享的签名 结束
			
			// 获取奖励的游戏秒数、用户sncode
			$u = $User->find($_SESSION['uid']);
			if ($u && $u['id'] != '') {
				$this->assign('prizesec',$u['prizesec']);
				$this->assign('sncode',$u['sncode']);
			}
			
			//
			$this->assign('acceptOk',"1");
			
			$this->display();
		}
		
	}
	
	public function index(){
		$Config = M('Config');
		$User = M('User');
		$uploadDir = "__PUBLIC__/Uploads/";
		
		//获取微信分享图片，分享标题，分享描述，分享URL
		$cfg_wx_share_title = $Config->where("varname='cfg_wx_share_title'")->getField('value');
		$this->assign('cfg_wx_share_title',$cfg_wx_share_title);
		
		$cfg_wx_share_desc = $Config->where("varname='cfg_wx_share_desc'")->getField('value');
		$this->assign('cfg_wx_share_desc',$cfg_wx_share_desc);
		
		$cfg_wx_share_pic = $Config->where("varname='cfg_wx_share_pic'")->getField('value');
		//$this->assign('cfg_wx_share_pic',$baseDomain."Public/Uploads/".$cfg_wx_share_pic);
		$this->assign('cfg_wx_share_pic',$cfg_wx_share_pic);
		
		$cfg_wx_share_url = $Config->where("varname='cfg_wx_share_url'")->getField('value');
		$this->assign('cfg_wx_share_url',$cfg_wx_share_url);
		
		
		$cfg_wx_share_redirect = $Config->where("varname='cfg_wx_share_redirect'")->getField('value');
		$this->assign('cfg_wx_share_redirect',$cfg_wx_share_redirect);
		
		$cfg_appid = $Config->where("varname='cfg_appid'")->getField('value');
		$cfg_screct = $Config->where("varname='cfg_screct'")->getField('value');
		// 获取分享的签名 开始
		vendor("WeixinShare.jssdk");
		$jssdk = new JSSDK($cfg_appid, $cfg_screct);
		$signPackage = $jssdk->GetSignPackage();
		$this->assign('signPackage',$signPackage);
		// 获取分享的签名 结束
		
		//判断活动是否结束
		if($this->isGameEnd()){
			
			$cfg_game_finish=$Config->where("varname='cfg_game_finish'")->getField('value');
			
			
			$this->assign('cfg_game_finish',$cfg_game_finish);
		
			$this->display('gameFinish');
			
		} else {
			
		//判断是否为微信授权模式，如果是，跳转微信授权页面
		
		
		$cfg_isoauth_open = $Config->where("varname='cfg_isoauth_open'")->getField('value');
		
		$need_login = 1; //默认需要弹填写信息框
		
		// 获取分享人的信息
		// 从接收参数改成了session或者cookie获取
		$shareId = $_SESSION['shareId'];
		if (empty($shareId)) {
			$shareId = $_REQUEST['shareId'];
		}
		
		
		//
		//$cfg_isoauth_open = 0;
		
		// 判断是否已经获取过个人信息
		$getInfo = $_SESSION['getInfo'];
		
		//if($cfg_isoauth_open=='1' && (empty($_SESSION['uid']))) {
		if($cfg_isoauth_open=='1') {
			$cfg_oauth_cb_url = $Config->where("varname='cfg_oauth_cb_url'")->getField('value');
			// 拼接分享人的信息
			$cfg_oauth_cb_url .= '?shareId='.$shareId;
			
			
			//授权判断
			if (empty($openid)){
				if (empty($_REQUEST["code"])) {
					$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$cfg_appid."&redirect_uri=".urlencode($cfg_oauth_cb_url)."&response_type=code&scope=snsapi_userinfo&state=blinq#wechat_redirect";

					redirect($url);
			
				}else{
					$code = $_REQUEST['code'];

					$accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $cfg_appid . "&secret=" . $cfg_screct . "&code=$code&grant_type=authorization_code";
					$ch = curl_init($accessTokenUrl);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					//curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');
					curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
					$info = curl_exec($ch);
					$dataJson = json_decode($info, true);
					$openid = $dataJson['openid'];
					$access_token = $dataJson['access_token'];
					session("wxid", $openid);
					
					//
					$cookieStr = '{"openid":"'.$openid.'","date":"20111212"}';
					$this->setCookieVal($cookieStr);
					
					// 拉取用户信息
					$userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
					$ch = curl_init($userInfoUrl);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					//curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');
					curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
					$info = curl_exec($ch);
					$dataJson = json_decode($info, true);
					
					$headimgurl = $dataJson['headimgurl'];
					$nickname = $dataJson['nickname'];
					
					
					// 判断wxid是否已经配置过，如果存在并且填写过信息，则不需要显示填写信息框
					
					$condition['wxid'] = $openid;
					$userList = $User->where($condition)->find();
					
					$this->assign("headimgurl",$info);
					
					if($userList && count($userList) > 0){
						$userphone = $userList['userphone'];
						if (!empty($userphone) && $userphone != 'none') {
							$need_login = 0; //表示填写过信息，不需要显示填写信息框
						}
						
						//获取用户ID
						$uid = $userList['id'];
						session("uid",$uid);
						
						//
						if (!empty($nickname)) {
							$userList['username'] = $nickname;
							$userList['headimgurl'] = $headimgurl;
							$User->save($userList);
						}
						
					} else {
						$userdata['username'] = $nickname;
						$userdata['userphone'] = 'none';
						$userdata['is_exchange'] = '0';
						$userdata['wxid'] = $openid;
						$userdata['headimgurl'] = $headimgurl;
						$userdata['regtime'] = date("Y-m-d H:i:s");
						$uid = $User->add($userdata);
						session("uid",$uid);
						
					}
					
					// 
					/* if ($shareId != '' && $shareId != '0' && $shareId != $_SESSION['uid']) {
						$Friend = M('Friend');
						$f_arr['uid']=$shareId;
						$f_arr['fid']=$_SESSION['uid'];
						$shareResult = $Friend->where($f_arr)->find();
						if (empty($shareResult) || $shareResult['uid'] == '') {
							$f_arr['sharetime'] = date("Y-m-d H:i:s");
							$Friend->add($f_arr);
						
						
						}
						
					} */
					
					
					
					
					
				}
			}
		} else {
			
			/* session("wxid", "oAMbVsyj3BblAIbtg6KmDpDIhdkI");
			session("uid", "20"); */
			
			// 需要重新看看用户是否已经登记过手机号码（因为无论如何都是开启了授权模式，所以走了次分支，肯定是用户刚刚走过了新流程入口，session非空）
			$uarr = $User->find($_SESSION['uid']);
			if ($uarr && count($uarr) > 0) {
				$userphone = $uarr['userphone'];
				if (!empty($userphone) && $userphone != 'none') {
					$need_login = 0; //表示填写过信息，不需要显示填写信息框
				}
				
			}
			
			
		}
		
		
		// renyuanshu -> rys
		/* if (!empty($shareId) && $shareId != '') {
			$Config->execute("update tp_user as a set a.rys=(select count(*) from tp_friend as b where b.uid!=0 and b.fid!=0 and b.uid=".$shareId.")
								where a.id=".$shareId);
		}
		$Config->execute("update tp_user as a set a.rys=(select count(*) from tp_friend as b where b.uid!=0 and b.fid!=0 and b.uid=".$_SESSION['uid'].")
								where a.id=".$_SESSION['uid']); */
		
		// 重置prizesec
		$Config->execute("update tp_user as u set u.prizesec=0 where u.id=".$_SESSION['uid']);
		
		
		$this->assign('need_login',$need_login); 
		
		//获取首页的标题
		$cfg_homepage_title = $Config->where("varname='cfg_homepage_title'")->getField('value');
		$this->assign('cfg_homepage_title',$cfg_homepage_title);
		
		//
		$this->assign('uploadDir',$uploadDir);
		
		// 获取首页的背景图
		$cfg_homepage_bg = $Config->where("varname='cfg_homepage_bg'")->getField('value');
		$this->assign('cfg_homepage_bg',$cfg_homepage_bg);
		
		//获取统计代码
		$cfg_tongji_code = $Config->where("varname='cfg_tongji_code'")->getField('value');
		$this->assign('cfg_tongji_code',$cfg_tongji_code);
		
		//获取banner路径
		$cfg_top_banner = $Config->where("varname='cfg_top_banner'")->getField('value');
		$this->assign('cfg_top_banner',$cfg_top_banner);
		
		//获取活动时间，活动规则，活动奖品，活动说明等信息
		$cfg_game_star_time = $Config->where("varname='cfg_game_star_time'")->getField('value');
		$this->assign('cfg_game_star_time',$cfg_game_star_time);
		$cfg_game_end_time = $Config->where("varname='cfg_game_end_time'")->getField('value');
		$this->assign('cfg_game_end_time',$cfg_game_end_time);
		
		$cfg_game_rule = $Config->where("varname='cfg_game_rule'")->getField('value');
		$this->assign('cfg_game_rule',$cfg_game_rule);
		
		
		$cfg_game_ruleimg = $Config->where("varname='cfg_game_ruleimg'")->getField('value');
		$this->assign('cfg_game_ruleimg',$cfg_game_ruleimg);
		
		// 获取sncode、is_exchange
		$udata = $User->find($_SESSION['uid']);
		$this->assign('sncode',$udata['sncode']);
		$this->assign('is_exchange',$udata['is_exchange']);
		if ($udata['is_exchange'] == '1') {
			$Exchange = M('Exchange');
			$exdata = $Exchange->query("select s.shopname from tp_exchange as e join tp_shop as s on e.shopid=s.id where e.uid=".$_SESSION['uid']);
			$this->assign('shopname',$exdata[0]['shopname']);
		}
		
		// 获取score
		$Score = M('Score');
		$sdata = $Score->where("uid=".$_SESSION['uid'])->find();
		$this->assign('score',$sdata['score']);
		
		
		$this->display();
		
		}
		
		
    }
    
    public function getSncode() {
    	if (!defined('IN_SYS')) {
    		echo json_encode(array('status'=>'ng','msg'=>'非法操作，获取领奖码失败！'));
    		exit;
    	}
    	
    	$User = M('User');
    	$u = $User->find($_SESSION['uid']);
    	$sncode = $u['sncode'];
    	if (empty($sncode) || $sncode == '') {
    		$sncode = $this->generalSNKey();
    		$f = $User->where("id=".$_SESSION['uid'])->setField("sncode",$sncode);
    		if (!$f) {
    			echo json_encode(array('status'=>'ng','msg'=>'获取领奖码失败！'));
    			exit;
    		}
    	}
    	
    	echo json_encode(array('status'=>'ok','msg'=>'获取领奖码成功！','sncode'=>$sncode));
    	exit;
    }
    
    public function prizesec() {
    	if (!defined('IN_SYS')) {
    		echo json_encode(array('status'=>'ng','msg'=>'非法操作，保存奖励失败！'));
    		exit;
    	}
    	
    	$User = M('User');
    	$f = $User->execute("update tp_user as u set u.prizesec=u.prizesec+5 where u.id=".$_SESSION['uid']);
    	
    	if (!$f) {
    		echo json_encode(array('status'=>'ng','msg'=>'保存奖励失败！'));
    		exit;
    	} else {
    		$u = $User->find($_SESSION['uid']);
    		echo json_encode(array('status'=>'ok','msg'=>'保存奖励成功！','prizesec'=>$u['prizesec']));
    		exit;
    	}
    	
    }
    
    public function kssq() {
    	if (!defined('IN_SYS')) {
    		echo json_encode(array('status'=>'ng','msg'=>'非法操作！'));
    		exit;
    	}
    	
    	$data['userphone'] = $_POST['userphone'];
    	$data['realname'] = $_POST['realname'];
    	$User = M('User');
    	$f = $User->where("id=".$_SESSION['uid'])->save($data);
    	 
    	if (!$f) {
    		echo json_encode(array('status'=>'ng','msg'=>'保存个人信息失败！'));
    		exit;
    	} else {
    		echo json_encode(array('status'=>'ok','msg'=>'保存个人信息成功！'));
    		exit;
    	}
    	 
    }
    
    public function qrdk() {
    	if (!defined('IN_SYS')) {
    		echo json_encode(array('status'=>'ng','msg'=>'非法操作！'));
    		exit;
    	}
    	 
    	$User = M('User');
    	$udata = $User->find($_SESSION['uid']);
    	if ($udata && $udata['is_exchange'] == '1') {
    		echo json_encode(array('status'=>'ng','msg'=>'抱歉，您已经抵扣过了！'));
    		exit;
    	}
    	
    	//
    	$shopcode = $_POST['shopcode'];
    	$Shop = M('Shop');
    	$shopdata = $Shop->where("shopcode='".$shopcode."'")->find();
    	if (!(count($shopdata) > 0)) {
    		echo json_encode(array('status'=>'ng','msg'=>'门店码不存在，请重新输入！'));
    		exit;
    	}
    	
    	$sncode = $udata['sncode'];
    	$Score = M('Score');
    	$sdata = $Score->where("uid=".$_SESSION['uid'])->find();
    	
    	$ex_arr['exchangedatetime'] = date("Y-m-d H:i:s");
    	$ex_arr['uid'] = $_SESSION['uid'];
    	$ex_arr['score'] = $sdata['score'];
    	$ex_arr['sncode'] = $sncode;
    	$ex_arr['shopid'] = $shopdata['id'];
    	
    	//开始事务处理
    	 
    	$model = new Model();
    	$model->startTrans();
    	$flag = false;
    	$ex_add_result = $model->table(C('DB_PREFIX').'exchange')->add($ex_arr);
    	
    	if ($ex_add_result) {
    		$udata['is_exchange'] = 1;
    		$user_upd_result = $User->save($udata);
    		if ($user_upd_result) {
    			$model->commit();
    			$flag = true;
    		}
    		
    	}
    	
    	if (!flag) {
    		$model->rollback();
    		echo json_encode(array('status'=>'ng','msg'=>'抱歉，抵扣失败！'));
    		exit;
    	} else {
    		echo json_encode(array('status'=>'ok','msg'=>'恭喜，您已成功抵扣领奖码：'.$sncode,
    				'score'=>$sdata['score'],'shopname'=>$shopdata['shopname']));
    		exit;
    	}
    
    }
    
    //
    public function doReg(){
    	
    	$Config = M('Config');
    	$cfg_isoauth_open = $Config->where("varname='cfg_isoauth_open'")->getField('value');
    	
    	//如果是微信授权的，没注册的，直接添加一笔记录
    	if($cfg_isoauth_open=='1'){
    		$user_array['username']= $_POST['username'];
    		$user_array['userphone'] = $_POST['userphone'];
    		$user_array['wxid']= $_SESSION['wxid'];
    		$user_array['regtime']= date("Y-m-d H:i:s");
    		$User = M("User"); // 实例化User对象
    		$lastId = $User->add($user_array);
    		if(!$lastId){
    			echo json_encode(array('status'=>'ng','message'=>'新增用户失败！'));
    			exit;
    		}
    		 
    		session("uid",$lastId);//获取最新用户ID
    	}else{
    		//判断用户的手机是否存在，如果手机存在，判断是否用户名输错，如果都不存在，注册新的一笔记录
    		/* 判断用户是否存在 */
    		$User = M("User"); // 实例化User对象
    		$user_array['userphone'] =$_POST['userphone'];
    		$user_result=$User->where($user_array)->find();
    		
    		if($user_result != null){
    			$user_array['username']=$_POST['username'];
    			$user_array['wxid']='none';
    			$user_result=$User->where($user_array)->find();
    				
    			if($user_result==null){//用户名错误了
    				echo json_encode(array('status'=>'ng','message'=>'用户名错误！'));
    				exit;
    			}else{
    				
    				session("uid",$user_result['id']);//获取最新用户ID
    				session("username",$user_result['username']);
    				session("userphone",$user_result['userphone']);
    			}
    		}else{
    			$user_array['username']= $_POST['username'];
    			$user_array['userphone'] = $_POST['userphone'];
    			$user_array['wxid']= 'none';//没有微信ID
    			$user_array['regtime']= date("Y-m-d H:i:s");
    			$User = M("User"); // 实例化User对象
    			$lastId = $User->add($user_array);
    			if(!$lastId){
    				echo json_encode(array('status'=>'ng','message'=>'新增用户失败！'));
    				exit;
    			}
    			 
    			session("uid",$lastId);//获取最新用户ID
    			session("username",$_POST['username']);
    			session("userphone",$_POST['userphone']);
    		}
    	}
    	echo json_encode(array('status'=>'ok'));
    	exit;
    }
    
    public function submitScore() {
    	if (!defined('IN_SYS')) {
    		echo json_encode(array('status'=>'ng','msg'=>'非法操作，保存失败！'));
    		exit;
    	}
    	
    	//
    	session("shareDesc",$_POST['shareDesc']);
    	//
    	
    	$Score = M("Score"); // 实例化对象
    	$data = $Score->where("uid=".$_SESSION['uid'])->find();
    	
    	$score_array['uid']=$_SESSION['uid'];
    	$score_array['score']=$_POST['score'];
    	$score_array['joindate']=date("Y-m-d H:i:s");
    	
    	$lastId = '';
    	if (count($data) > 0) {
    		if (intval($data['score']) < intval($_POST['score'])) {
    			$score_array['id'] = $data['id'];
    			$lastId = $Score->save($score_array);
    		}
    	} else {
    		$lastId = $Score->add($score_array);
    	}
    	
    	
    	if(!$lastId){
    		echo json_encode(array('status'=>'ng','msg'=>'保存失败！','uid'=>$_SESSION['uid'],'lastId'=>$_POST['score']));
    		exit;
    	}
    	
    	echo json_encode(array('status'=>'ok','msg'=>'保存成功！'));
    	exit;
    }
    
    public function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
    {
    	if($code == 'UTF-8')
    	{
    		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
    		preg_match_all($pa, $string, $t_string);
    
    		if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
    		return join('', array_slice($t_string[0], $start, $sublen));
    	}
    	else
    	{
    		$start = $start*2;
    		$sublen = $sublen*2;
    		$strlen = strlen($string);
    		$tmpstr = '';
    
    		for($i=0; $i< $strlen; $i++)
    		{
    		if($i>=$start && $i< ($start+$sublen))
    		{
    		if(ord(substr($string, $i, 1))>129)
    			{
    			$tmpstr.= substr($string, $i, 2);
    		}
    		else
    		{
    		$tmpstr.= substr($string, $i, 1);
    		}
    		}
    		if(ord(substr($string, $i, 1))>129) $i++;
    		}
    			//if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
    			return $tmpstr;
    	}
    	}
}